import React, { Component } from 'react';
import { Button, Balloon, Message, Tab } from '@teamix/ui';
import docs from 'utils/docs';
import ListLoading from 'atComponents/ListLoading';
import { ButtonIcon } from '@alife/devops-ui';
import BtnConfirm from './btnConfirm';
import track from 'utils/track';
import { navigateOpen } from 'utils/router';
import intl from '../../../../../../../../../locale';

export default class SlsService extends Component {
  state = {
    loading1: true,
    loading2: true,
  };

  componentDidMount() {
    // 获取sls授权状态
    this.props.getAuthorizationStatus();
  }

  openSlsAuthPage = () => {
    const { authRedirectUrl } = this.props.slsInfo || {};
    if (!authRedirectUrl) return;
    track({
      action: 'to_authorized_services',
      page: '',
      type: 'sls',
      control: '',
    });
    const openedWindow = navigateOpen(authRedirectUrl);
    openedWindow.document.title = intl.get({
      id: 'code-assets.audit.containers.slsService.AuthorizeSlsServices',
      defaultMessage: '授权SLS服务',
    });
    const windowChecker = setInterval(() => {
      if (openedWindow.location.pathname === '/oauth/aliyun/success') {
        window.clearInterval(windowChecker);
        this.props.slsAuthorize('AliyunRDCCodeAuditRole');
        if (!openedWindow.closed) {
          openedWindow.close();
        }
      }
    }, 500);
  };

  removeSlsAuth = () => {
    const { authorization_id } = this.props.slsInfo || {};
    if (!authorization_id) return;
    this.props.removeAuth(authorization_id);
  };

  onLoad1 = () => {
    this.setState({
      loading1: false,
    });
  };

  onLoad2 = () => {
    this.setState({
      loading2: false,
    });
  };

  renderContent = () => {
    const { loading1, loading2 } = this.state;
    const { isSlsAuthLoading, authorization_id, authUser, projectName, logstoreName } =
      this.props.slsInfo;
    if (isSlsAuthLoading) {
      return <ListLoading style={{ height: '200px' }} />;
    }
    if (!authorization_id) {
      return (
        <div className="sls-get-auth">
          <div className="goto-auth">
            <span>
              {intl.get({
                id: 'code-assets.audit.containers.slsService.BasedOnAlibabaCloudLog',
                defaultMessage:
                  '基于阿里云日志服务（SLS），支持将企业日志原始记录自动写入您绑定的 SLS 空间，进行保存和数据分析处理。',
              })}
            </span>
            <Button type="primary" text onClick={this.openSlsAuthPage}>
              {intl.get({
                id: 'code-assets.audit.containers.slsService.AuthorizeSlsServices',
                defaultMessage: '授权SLS服务',
              })}
            </Button>
          </div>
          <Message type="notice" className="sls-message">
            <span>
              {intl.get({
                id: 'code-assets.audit.containers.slsService.CodeupIsDeeplyIntegratedWith',
                defaultMessage:
                  'Codeup 与日志服务深度结合，企业首次绑定日志服务可获得7日免费试用空间，超期由 SLS 日志服务单独收费，支持随时取消授权。',
              })}
            </span>
            <a
              href={docs('sls-serve-cost')}
              className="sls-message-btn"
              target="_blank"
              rel="noreferrer"
            >
              {intl.get({
                id: 'code-assets.audit.containers.slsService.ViewSlsBillingInstructions',
                defaultMessage: '查看 SLS计费说明',
              })}
            </a>
          </Message>
        </div>
      );
    }
    // https://sls.console.aliyun.com/lognext/project/<Project名称>/logsearch/<日志库名称>
    const sls_url = `https://sls.console.aliyun.com/lognext/project/${projectName}/logsearch/${logstoreName}?hiddenEtl=true`;
    const sls_dash = `https://sls.console.aliyun.com/lognext/project/${projectName}/dashboard/codeup-logstore_audit_center_cn?isShare=true&hideTopbar=true&hideSidebar=true`;
    const sls_serve = `https://sls.console.aliyun.com/lognext/project/${projectName}/logsearch/codeup-logstore`;
    return (
      <div className="sls-has-auth">
        <div className="sls-has-auth-info">
          <span>
            {intl.get(
              {
                id: 'code-assets.audit.containers.slsService.AuthorizerAuthuser',
                defaultMessage: '授权人：{authUser}',
              },
              { authUser },
            )}
          </span>
          <div className="btn-group">
            <a href={sls_serve} target="_blank" rel="noreferrer">
              {intl.get({
                id: 'code-assets.audit.containers.slsService.GoToLogService',
                defaultMessage: '前往日志服务',
              })}
            </a>
            <BtnConfirm
              projectName={projectName}
              trigger={
                <Button text className="warnning-btn">
                  {intl.get({
                    id: 'code-assets.audit.containers.slsService.RevokeAuthorization',
                    defaultMessage: '解除授权',
                  })}
                </Button>
              }
              onClick={() => {
                this.removeSlsAuth();
              }}
            />
          </div>
        </div>
        <div className="sls-project-desc">
          {intl.get(
            {
              id: 'code-assets.audit.containers.slsService.UseAProjectnameNamedProject',
              defaultMessage: '将使用名为 {projectName} 的 Project 用于同步日志数据',
            },
            { projectName },
          )}
        </div>
        <Tab
          className="sls-iframe-tab"
          navStyle={{ border: 'none', padding: 0 }}
          shape="capsule"
          size="small"
          animation={false}
        >
          <Tab.Item
            title={intl.get({
              id: 'code-assets.audit.containers.slsService.RawLog',
              defaultMessage: '原始日志',
            })}
          >
            {loading1 ? <ListLoading style={{ height: '600px' }} /> : null}
            <iframe
              src={sls_url}
              onLoad={this.onLoad1}
              width="100%"
              height="800px"
              style={{ border: 0, display: loading1 ? 'none' : 'block' }}
            />
          </Tab.Item>
          <Tab.Item
            title={intl.get({
              id: 'code-assets.audit.containers.slsService.LogReports',
              defaultMessage: '日志报表',
            })}
          >
            {loading2 ? <ListLoading style={{ height: '600px' }} /> : null}
            <iframe
              src={sls_dash}
              onLoad={this.onLoad2}
              width="100%"
              height="2500px"
              style={{ border: 0, display: loading2 ? 'none' : 'block' }}
            />
          </Tab.Item>
        </Tab>
      </div>
    );
  };

  render() {
    return (
      <div className="sls-service-container">
        <div className="sls-service-container-title">
          <span className="sls-service-container-title-text">
            {intl.get({
              id: 'code-assets.audit.containers.slsService.LogService',
              defaultMessage: '日志服务',
            })}
          </span>
          <Balloon.Tooltip
            className="sls-service-container-help-tooltip"
            trigger={<ButtonIcon name="question-line" />}
            align="t"
          >
            <a href={docs('sls-serve-help')} target="_blank" rel="noreferrer">
              {intl.get({
                id: 'code-assets.audit.containers.slsService.HowDoIUseLog',
                defaultMessage: '如何使用日志服务？',
              })}
            </a>
          </Balloon.Tooltip>
        </div>
        {this.renderContent()}
      </div>
    );
  }
}
